package com.myorigin.weblog.jwt.handle;

import com.myorigin.weblog.common.enums.ResponseCodeEnum;
import com.myorigin.weblog.common.utils.Response;
import com.myorigin.weblog.jwt.exception.UsernameOrPasswordNullExeception;
import com.myorigin.weblog.jwt.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 自定义认证失败处理器 RestAuthenticationSuccessHandler
 * 用户登录后，我们还需要处理其对应的结果，如登录成功，则返回 Token 令牌，登录失败，则返回对应的提示信息。
 * 在 Spring Security 中，AuthenticationFailureHandler 和 AuthenticationSuccessHandler 是用于处理身份验证失败和成功的接口。
 * 它们允许您在用户身份验证过程中自定义响应，以便更好地控制和定制用户体验。
 */
@Component
@Slf4j
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler{
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.warn("AuthenticationException: ",exception);
        if(exception instanceof UsernameOrPasswordNullExeception){
            //用户名或密码为空
            ResultUtil.fail(response, Response.fail(exception.getMessage()));
        }else if(exception instanceof BadCredentialsException){
            // 用户名或密码错误
            ResultUtil.fail(response, Response.fail(ResponseCodeEnum.USERNAME_OR_PWD_ERROR));
        }
        // 登录失败
        ResultUtil.fail(response, Response.fail(ResponseCodeEnum.LOGIN_FAIL));
    }
}
